var SGModel           = require('./SGModel');
var SGProto           = require('./SGProto');
var SGLogic           = require('./SGLogic');
var RoomProto         = require('../../API/RoomProto');
var HallApi           = require('../../API/HallAPI');
var RoomAPI           = require('../../API/RoomAPI');
var RoomMessageRouter = 'game.gameHandler.roomMessageNotify';
var GameMessageRouter = 'game.gameHandler.gameMessageNotify';

cc.Class({
	extends: cc.Component,
	properties: {
	},

	onLoad: function () {
		this.seatNames = ['北京', '上海', '广州', '天津', '重庆', '香港', '南京', '澳门', '海口', '深圳'];
		this.msgbg = cc.find('msgbg', this.node);
		this.headSprite = cc.find('head', this.node).getComponent(cc.Sprite);
		this.nameLabel = cc.find('name', this.node).getComponent(cc.Label);
		this.idLabel = cc.find('id', this.node).getComponent(cc.Label);
		this.robSprite = cc.find('robstate', this.node).getComponent(cc.Sprite);
		this.scoreNode = cc.find('scorebg', this.node);
		this.scoreNodePos = this.scoreNode.getPosition();
		this.scoreLabel = cc.find('gold', this.scoreNode).getComponent(cc.Label);
		this.goldNode = cc.find('icon', this.scoreNode);
		this.bankerNode = cc.find('banker', this.node);
		this.readyNode = cc.find('ready', this.node);
		this.readyNodePos = this.readyNode.getPosition();
		this.fangzhuNode = cc.find('fangzhu', this.node);
		this.light = this.node.getChildByName('light');
		this.node.active = false;

		this.winScoreNode = this.node.getChildByName('winscore');
		this.loseScoreNode = this.node.getChildByName('losescore');
		Global.MessageCallback.addListener('RoomMessagePush', this);
		Global.MessageCallback.addListener('GameMessagePush', this);
		Global.MessageCallback.addListener('ReConnectSuccess', this);
	},

	setIndex: function (index) {
		this.index = index;
		if (this.index == 0 && cc.visibleRect.width/cc.visibleRect.height > 1.8) {
			console.log("index", index);
			this.readyNode.x = cc.visibleRect.width/2-1334/2+this.readyNodePos.x;
			this.scoreNode.x = cc.visibleRect.width/2-1334/2+this.scoreNodePos.x;
		}
	},

	showSeat: function () {
		let names = ['msgbg', 'head', 'headedg', 'fangzhu', 'name', 'id', 'robstate', 'scorebg', 'banker', 'winscore', 'losescore', 'light', 'text', 'ready', 'offline'];
		for (let name of names) {
			let node = this.node.getChildByName(name);
			if (node) {
				node.active = false;
			}
		}
		this.refrushName();
	},

	hideSeat: function () {
		if (this.seatNode) {
			this.seatNode.active = false;
		}
		let names = ['msgbg', 'head', 'headedg', 'name', 'id', 'robstate', 'scorebg', 'banker', 'winscore', 'losescore', 'ready'];
		for (let name of names) {
			let node = this.node.getChildByName(name);
			if (node) {
				node.active = true;
			}
		}
	},

	refrushName: function () {
		if (!this.seatNode) {
			let node = new cc.Node();
			node.setPosition(this.msgbg.getPosition()); 
			node.parent = this.node;  

			let bgNode = new cc.Node();
			bgNode.parent = node;
			cc.loader.loadRes('Game/Common/citybg', cc.SpriteFrame, (err, spriteFrame) => {
				if (!err) {
					bgNode.addComponent(cc.Sprite).spriteFrame = spriteFrame;
				}
				if (this.msgbg.width > this.msgbg.height) {
					bgNode.rotation = 90;
					bgNode.width = this.msgbg.height;
					bgNode.height = this.msgbg.width;
				}
				else {
					bgNode.height = this.msgbg.height;
					bgNode.width = this.msgbg.width;
				}
			});
			let labelNode = new cc.Node();
			labelNode.color = new cc.Color(255, 255, 255);
			labelNode.name = 'Label'; 
			labelNode.parent = node;
			labelNode.y = 10;
			let label = labelNode.addComponent(cc.Label);
			label.fontSize = 25;
			label.string = this.seatNames[this.getChairID()];     

			bgNode.on(cc.Node.EventType.TOUCH_END, this.onSeatClick.bind(this), this); 
			this.seatNode = node;

			let arrow = new cc.Node();
			arrow.parent = node;
			arrow.y = -15;
			cc.loader.loadRes('Game/Common/jiantou', cc.SpriteFrame, (err, spriteFrame) => {
				if (!err) { arrow.addComponent(cc.Sprite).spriteFrame = spriteFrame; }
			});
			arrow.setScale(0.8);
		}
		else {
			this.seatNode.active = true;
			cc.find('Label', this.seatNode).getComponent(cc.Label).string = this.seatNames[this.getChairID()];  
		}
	},

	onSeatClick: function () {
		if (SGModel.isUnionCreate()) {
			let user = SGModel.getUserByChairID(SGModel.getMyChairID());
			if (user.userInfo.score < SGModel.getGameRule().scoreLowLimit) {
				Global.DialogManager.addTipDialog('金币不足，不能入座');
				return;
			}
		}
		Global.NetworkManager.notify(RoomMessageRouter, RoomProto.getUserChangeSeatNotify(SGModel.getMyChairID(), this.getChairID()));
	},

	getChairID: function (chairID) {
		if (SGModel.getMyChairID() >= SGModel.getChairCount()) {
			return this.index;
		}
		else {
			return (SGModel.getMyChairID()+this.index)%SGModel.getChairCount();
		}
	},

	gameInit () {
		if (typeof(this.index) != 'number') { return; } /* 未使用，等待销毁 */ 
		this.node.active = true;
		let user = SGModel.getUserByChairID(this.getChairID());
		if (!user) {
			let ready = (SGModel.getUserByChairID(SGModel.getMyChairID()).userStatus&RoomProto.userStatusEnum.READY);
			if ((SGModel.getCurBureau() == 0 && !ready) || (SGModel.getMyChairID() >= SGModel.getChairCount() && SGModel.getGameRule().canEnter)) {
				this.showSeat();
			}
			else {
				this.hideSeat();
				this.node.active = false;
			}
			return;
		}
		else {
			this.hideSeat();
		}

		this.nameLabel.string = user.userInfo.nickname;
		/* this.idLabel.string = Math.floor(user.userInfo.score); */
		this.idLabel.string = SGModel.getCurScore(this.getChairID());
		let is_creator = (SGModel.getRoomCreatorChairID() == this.getChairID());
		this.fangzhuNode.active = is_creator;
		Global.CCHelper.updateSpriteFrame(user.userInfo.avatar, this.headSprite);

		if (SGModel.getGameStatus() == SGProto.gameStatus.NONE) {
			this.scoreNode.active = false;
			this.bankerNode.active = false;
			this.readyNode.active = (user.userStatus&RoomProto.userStatusEnum.READY);
		}
		else if (SGModel.getGameStatus() == SGProto.gameStatus.ROB_BANK) {
			this.scoreNode.active = false;
			this.bankerNode.active = false;
			this.readyNode.active = false;
		}
		else if (SGModel.getGameStatus() >= SGProto.gameStatus.POUR_SCORE) {
			this.setPourScore(SGModel.getPourScoreByChairID(this.getChairID()));
			this.bankerNode.active = (this.getChairID() == SGModel.getBankerChairID());
			this.readyNode.active = false;
		}
		this.setRobScale();
		this.showResultScore();
		cc.find('offline', this.node).active = (user.userStatus&RoomProto.userStatusEnum.OFFLINE) > 0;
	},

	/*
	 * 设置抢庄倍数
	 */
	setRobScale: function () {
		let scale = SGModel.getRobScaleByChairID(this.getChairID());
		this.robSprite.node.active = false;
		if (scale == null) {
			return;
		}
		if (SGModel.getGameStatus() == SGProto.gameStatus.ROB_BANK && SGModel.getBankerChairID() == null) {
			let array = ['buqiang', 'qiang1', 'qiang2', 'qiang3', 'qiang4'];
			let url = 'Game/Niuniu/'+array[scale];
			Global.CCHelper.updateSpriteFrame(url, this.robSprite); 
			this.robSprite.node.active = true;
		}
		else {
			if (SGModel.getBankerChairID() == this.getChairID() && (SGModel.getGameType() != SGProto.gameType.PAIDAZHUANG)) {
				let url = 'Game/Niuniu/' + ['', '1bei', '2bei', '3bei', '4bei'][scale];
				Global.CCHelper.updateSpriteFrame(url, this.robSprite); 
				this.robSprite.node.active = true;
			}
		}
	},

	/*
	 * 设置下分
	 */
	setPourScore: function (score, animal) {
		if (score == 0 || score == null) {
			this.scoreNode.active = false;
		}
		else {
			this.scoreLabel.string = score;
			this.scoreNode.active = true;
			if (animal) {
				let icon = cc.find('scorebg/icon', this.node);
				let icon_pos = icon.getPosition();
				let scorebg_pos = cc.find('scorebg', this.node).getPosition();
				let end_pos = cc.v2(scorebg_pos.x+icon_pos.x, scorebg_pos.y+icon_pos.y);
				Global.AudioManager.playSound('Game/Niuniu/NNAudio/fly_gold');
				for (let i = 0; i < 10; ++i) {
					let node = cc.instantiate(icon);
					node.setPosition(0, 0);
					node.parent = this.node;
					node.runAction(cc.sequence(
						cc.delayTime(0.08*i),
						cc.moveTo(0.3, end_pos),
						cc.removeSelf()
					));
				}
			}
		}
	},

	messageCallbackHandler: function(router, msg) {
		if (!SGModel.getGameInited()) { return; }
		if (router === 'RoomMessagePush') {
			if(msg.type === RoomProto.GET_ROOM_SCENE_INFO_PUSH) {
				this.gameInit();
			}
			else if(msg.type === RoomProto.USER_READY_PUSH) {
				if (msg.data.chairID == SGModel.getMyChairID() && SGModel.getCurBureau() == 0) {
					this.gameInit();
				}
				if (this.node.active && msg.data.chairID == this.getChairID()) {
					this.readyNode.active = true;
					this.robSprite.node.active = false;
					this.scoreNode.active = false;
				}
				if (this.node.active && msg.data.chairID == SGModel.getMyChairID()) {
					let user = SGModel.getUserByChairID(this.getChairID());
					if (user) {
						this.robSprite.node.active = false;
						this.scoreNode.active = false;
						this.readyNode.active = (user.userStatus&RoomProto.userStatusEnum.READY);
						this.bankerNode.active = (SGModel.getBankerChairID() == this.getChairID());
						this.winScoreNode.active = false;
						this.loseScoreNode.active = false;
					}
				}
			}
			else if(msg.type === RoomProto.USER_LEAVE_ROOM_RESPONSE) {
				/* if(msg.data.chairID == this.getChairID()) {
					this.node.active = false;
				} */
			}
			else if(msg.type === RoomProto.OTHER_USER_ENTRY_ROOM_PUSH) {
				if (msg.data.roomUserInfo.chairID == this.getChairID()) {
					this.gameInit();
				}
			}
			else if(msg.type === RoomProto.USER_LEAVE_ROOM_PUSH) {
				if (msg.data.roomUserInfo.chairID == this.getChairID()) {
					this.node.active = false;
				}
			}
			else if(msg.type === RoomProto.USER_CHANGE_SEAT_PUSH) {
				if (SGModel.getCurBureau() == 0) {
					this.gameInit();
				}
				else {
					if (SGModel.getMyUid() != msg.data.uid) {
						if (this.getChairID() == msg.data.fromChairID || this.getChairID() == msg.data.toChairID) {
							this.gameInit();
						}
					}
					else {
						this.gameInit();
					}
				}
			}
			else if(msg.type === RoomProto.ROOM_USER_INFO_CHANGE_PUSH) {
				let user = SGModel.getUserByChairID(this.getChairID());
				if (this.node.active && user) {
					/* this.idLabel.string = Math.floor(user.userInfo.score); */
					this.idLabel.string = Math.floor(SGModel.getCurScore(this.getChairID()));
				}
			}
			else if(msg.type === RoomProto.USER_OFF_LINE_PUSH) {
				if (msg.data.chairID == this.getChairID()) {
					cc.find('offline', this.node).active = true;
				}
			}
		}
		else if(router === 'GameMessagePush') {
			if(msg.type === SGProto.GAME_ROB_BANK_PUSH) {
				if (msg.data.chairID == this.getChairID()) {
					this.setRobScale(msg.data.robScale);
				}
			}
			else if(msg.type === SGProto.GAME_BANKER_PUSH) {
				this.setBanker(msg.data.robChairIDs, true);
			}
			else if(msg.type === SGProto.GAME_POUR_SCORE_PUSH) {
				if (msg.data.chairID == this.getChairID()) {
					this.setPourScore(msg.data.score, true);
					this.idLabel.string = SGModel.getCurScore(this.getChairID());
				}
			}
			else if(msg.type === SGProto.GAME_STATUS_PUSH) {
				if (msg.data.gameStatus == SGProto.gameStatus.SEND_CARDS) {
					let user = SGModel.getUserByChairID(this.getChairID());
					if (user) {
						this.robSprite.node.active = false;
						this.scoreNode.active = false;
						this.readyNode.active = (user.userStatus&RoomProto.userStatusEnum.READY);
						this.bankerNode.active = (SGModel.getBankerChairID() == this.getChairID());
						this.winScoreNode.active = false;
						this.loseScoreNode.active = false;
					}
				}
				if (msg.data.gameStatus != SGProto.gameStatus.NONE) {
					this.readyNode.active = false;
				}
				else {
					this.idLabel.string = SGModel.getCurScore(this.getChairID());
				}
			}
			else if(msg.type === SGProto.GAME_RESULT_PUSH) {
				if (SGModel.getUserByChairID(this.getChairID())) {
					this.showResultScore(true);
					this.idLabel.string = SGModel.getCurScore(this.getChairID());
				}
			}
			else if(msg.type === SGProto.GAME_CHAT_PUSH) {
				this.gameChat(msg.data);
			}
		} 
	},

	setBanker: function (robChairIDs, animal) {
		let is_banker = (SGModel.getBankerChairID() == this.getChairID());
		if (is_banker && animal && SGModel.getGameType() == SGProto.gameType.QIANGZHUANG) {
			Global.AudioManager.playSound('Game/Niuniu/NNAudio/rob_zhuang_ani');
		} 
		this.robSprite.node.active = false;
		if (robChairIDs && animal) {
			if (robChairIDs.indexOf(this.getChairID()) != -1) {
				this.light.active = true;
				this.light.runAction(cc.repeat(cc.sequence(cc.fadeOut(0.1), cc.fadeIn(0.1)), 5));
				if (is_banker) {
					this.bankerNodeMoveAnimal(2);
				}
				else {
					this.scheduleOnce(() => {
						this.light.active = false; 
						this.setRobScale();
					}, 2);
				}
			}
		}
		else if (SGModel.getGameType() == SGProto.gameType.PAIDAZHUANG && animal) {
			if (SGModel.getBankerChairID() == this.getChairID()) {
				this.bankerNodeMoveAnimal(0);
			}
		}
	},

	/*
	 * 庄家图标移动动画
	 */
	bankerNodeMoveAnimal: function (delay) {
		let bank_node = cc.find('BankerNode', this.node.parent);
		bank_node.setScale(1); 
		bank_node.setPosition(cc.v2(0, 0));
		let node_pos = this.node.getPosition();
		let banker_pos = this.bankerNode.getPosition();
		let end_pos = cc.v2(node_pos.x+banker_pos.x, node_pos.y+banker_pos.y);
		this.scheduleOnce(() => {
			bank_node.active = true;
			bank_node.runAction(cc.sequence(
				cc.moveTo(0.5, end_pos),
				cc.callFunc(() => {
					bank_node.active = false;
					this.light.active = false;
					this.bankerNode.active = true;
					this.setRobScale();
				})
			));
			bank_node.runAction(cc.scaleTo(0.5, 0.16));
		}, delay);
	},

	showResultScore: function (animal) {
		this.winScoreNode.active = false;
		this.loseScoreNode.active = false;
		let result = SGModel.getResult();
		if (result) {
			let score = Math.floor(result[this.getChairID()]);
			if (score >= 0) {
				this.winScoreNode.active = true;
				this.winScoreNode.getComponent(cc.Label).string = '+' + score;
				if (animal) {
					this.winScoreNode.x = -50;
					this.winScoreNode.runAction(cc.moveTo(0.2, cc.v2(0, 22)).easing(cc.easeIn(3.0)));
				}
			}
			else if(score < 0) {
				this.loseScoreNode.active = true;
				this.loseScoreNode.getComponent(cc.Label).string = ''+score; 
				if (animal) {
					this.loseScoreNode.x = -50;
					this.loseScoreNode.runAction(cc.moveTo(0.2, cc.v2(0, 22)).easing(cc.easeIn(3.0)));
				}
			}
		}
		if (animal) {
			let bankerID = SGModel.getBankerChairID();
			if (bankerID == null) {
				bankerID = 0;
				for (let i = 1; i < result.length; ++i) {
					if (result[i] > result[bankerID]) {
						bankerID = i;
					}
				}
			}
			if (this.getChairID() != bankerID) {
				return;
			}

			let winScore = [];
			for (let i = 0; i < SGModel.getChairCount(); ++i) {
				winScore[i] = 0;
			}
			let mypour = SGModel.getRobScaleByChairID(bankerID);
			if (mypour == null) {
				mypour = SGModel.getPourScoreByChairID(bankerID);
			}
			let myCards = SGModel.getHandCardsByChairID(this.getChairID());
			for (let i = 0; i < SGModel.getChairCount(); ++i) {
				let cards = SGModel.getHandCardsByChairID(i); 
				if (!cards || i == this.getChairID()) {
					continue;
				}
				let scale = 0;
				if (SGLogic.compareCards(myCards, cards) > 0) {
					scale = SGLogic.getScaleByCards(myCards, SGModel.getGameRule().scaleType);
					winScore[i] = scale * SGModel.getPourScoreByChairID(i) * mypour;
				}
				else {
					scale = SGLogic.getScaleByCards(cards, SGModel.getGameRule().scaleType);
					winScore[i] = -scale * SGModel.getPourScoreByChairID(i) * mypour;
				}
			}

			let has_lose = false;
			for (let i = 0; i < winScore.length; ++i) {
				if (winScore[i] < 0) {
					has_lose = true;
					this.goldMove(this.getChairID(), i);
				}
			}
			this.scheduleOnce(() => {
				for (let i = 0; i < winScore.length; ++i) {
					if (winScore[i] > 0) {
						this.goldMove(i, this.getChairID());
					}
				}
			}, (has_lose)? 1:0);
		}
	},

	/*
	 * 获取其他头像相对于自己头像的位置
	 * @param Number chairID 其他头像的chairID
	 */
	getHeadNodePosByChairID: function (chairID) {
		let mainLogic = this.node.parent.getComponent('SGMainDialog');
		let headNode = mainLogic.getHeadNodeByChairID(chairID);
		let myPos = this.node.getPosition();
		let otherPos = headNode.getPosition();
		return cc.v2(otherPos.x-myPos.x, otherPos.y-myPos.y);
	},

	/*
	 * 结算时金币移动
	 * @param Number startChairID 开始的头像chairID
	 * @param Number endChairID 结束的头像chairID
	 */
	goldMove: function (startChairID, endChairID) {
		let speed = 1500;
		let startPos = this.getHeadNodePosByChairID(startChairID);
		let endPos = this.getHeadNodePosByChairID(endChairID);
		let distance = Math.sqrt(Math.pow(startPos.x-endPos.x, 2)+Math.pow(startPos.y-endPos.y, 2));
		let dt = distance/speed;

		let callFunc = cc.callFunc(() => {
			Global.AudioManager.playSound('Game/Niuniu/NNAudio/xiazhu');
		});
		for (let i = 0; i < 10; ++i) {
			let icon = cc.find('scorebg/icon', this.node);
			let gold = cc.instantiate(icon);
			gold.parent = this.node;
			gold.setPosition(startPos);
			gold.runAction(cc.sequence(
				cc.delayTime(0.08*i),
				cc.moveTo(dt, endPos),
				callFunc,
				cc.removeSelf()
			));
		}
	},

	/*
	 * 游戏聊天
	 */
	gameChat: function (data) {
		let node = cc.find('text', this.node);
		let label = cc.find('Label', node);
		if (data.chairID == this.getChairID()) {
			let user = SGModel.getUserByChairID(this.getChairID());
			if (cc.find('emotion', node)) {
				cc.find('emotion', node).destroy();
			}
			if (data.type == 1) {
				label.active = false;
				let emotionNode = Global.CCHelper.getChatEmotionNode(data.msg, () => { node.active = false; });
				emotionNode.parent = node;
				emotionNode.setPosition(-70, 0);
				emotionNode.scaleX = node.scaleX;
				emotionNode.name = 'emotion';
				node.setContentSize(130, 110);
				node.active = true;
			}
			else if(data.type == 2) {
				let index = ['快点啊，等到花儿都谢了！', '不要吵了，不要吵了。专心玩游戏吧！', '怎么又断线了，网络怎么这么差啊！', '不要走，决战到天亮！', '底牌亮出来绝对吓死你！', '风水轮流转，底裤都输光！', '看我通杀全场，这些钱都是我的！', '不好意思啊，我要离开一会！'].indexOf(data.msg);
				Global.AudioManager.playSound('Game/ChatAudio/' + ((user.userInfo.sex == 0)? 'man/':'woman/') +index);
				label.active = true;
				label.getComponent(cc.Label).string = data.msg;
				this.scheduleOnce(() => {
					node.width = label.width+50;
					node.height = 58;
				}, 0);
				node.active = true;
				node.stopAllActions();
				node.runAction(cc.sequence(
					cc.delayTime(2),
					cc.callFunc(() => {
						node.active = false;
					})
				));
			}
		}
	},

	onDestroy: function () {
		Global.MessageCallback.removeListener('RoomMessagePush', this);
		Global.MessageCallback.removeListener('GameMessagePush', this);
		Global.MessageCallback.removeListener('ReConnectSuccess', this);
	},
});
